package org.example.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//登录检查的Filter
@Component
public class LonginCheckFilter extends ZuulFilter {
    //filter类型，前置filter
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //执行顺序
    @Override
    public int filterOrder() {
        return 1;
    }

    //该方法返回的boolean值如果为true,run方法就会执行，否则run方法就不执行
    //  /login 路径不需要做登录检查
    @Override
    public boolean shouldFilter() {
        //判断请求的RUI时候是登录"/login"
        //1.获取请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        //2.获取URI
        String requestURI = request.getRequestURI();

        //3.如果请求的路径是  "/login"  ，不做登录检查
        if(StringUtils.hasLength(requestURI) && requestURI.endsWith("login")){
            //是登录请求
            return false;
        }
        return true;
    }

    //核心业务逻辑方法：做登录检查 ， 如果请求头中没有token,说明未登录
    @Override
    public Object run() throws ZuulException {
        //1.获取请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        //设置编码
        response.setContentType("application/json;charset=utf-8");

        //2.获取请求头中的token
        String token = request.getHeader("token");

        //3.判断token，
        if(!StringUtils.hasLength(token)){
            //4.如果token为空，没登录，则返回执行登录， 并且阻止请求继续往下执行：不放行
            Map<String,Object> result = new HashMap<>();    //AJAXResult
            result.put("success",false);
            result.put("messsage","您未登录,请登录");
            //Fastjson
            //响应内容
            try {
                response.getWriter().print(JSON.toJSONString(result));

                //并且阻止请求继续往下执行：不放行
                currentContext.setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
